package com.baizhi.mall.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baizhi.mall.entity.mysql.BzFileDO;
import com.baizhi.mall.service.impl.BzFileServiceImpl;
import com.baizhi.mall.util.PageUtils;
import com.baizhi.mall.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/sys/file")
public class FileController {
    @Autowired
    private BzFileServiceImpl fileService;

    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    public  static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    public  static final String ASSET_KEY_ID = "LTAI5t9TEQFxos6xFobfwkdC";
    public  static final String ASSET_KEY_SECRET = "mhty40dwqBy7GH4WHV5k6jePXUYuoU";
    //仓库名
    public  static final String BUCKET = "bz_mall";

    @RequestMapping("upload")
    public ResultEntity upload(MultipartFile file, HttpServletRequest req, HttpSession session) throws IOException {
        // https://bz-mall-file.oss-cn-beijing.aliyuncs.com/20210125195023.jpg
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build("https://"+ENDPOINT, ASSET_KEY_ID, ASSET_KEY_SECRET);
        // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 目录  文件名也不要使用 原文件名
        String dir = simpleDateFormat.format(date) + "/";
        // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
        String oldFileName = file.getOriginalFilename();
        String newFileName = UUID.randomUUID().toString() + "_" +oldFileName;
        ossClient.putObject(BUCKET,dir + newFileName , inputStream);
        // 关闭OSSClient。
        ossClient.shutdown();
        //获取用户名
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        String username = (String)requestAttributes.getAttribute("username",RequestAttributes.SCOPE_SESSION);
        //
        BzFileDO fileDO = new BzFileDO(null,"https://"+BUCKET+"."+ENDPOINT+"/"+newFileName,
                newFileName,oldFileName,date,username);
        fileService.save(fileDO);
        return ResultEntity.ok();
    }
    @PostMapping("list")
    public ResultEntity showAll(@RequestBody Map<String,Object> param){
        System.out.println("param = " + param);
        PageUtils pageUtils = fileService.queryAllFileByPage(param);
        return ResultEntity.ok(pageUtils);
    }
    @DeleteMapping("/remove/{id}")
    public ResultEntity remove(@PathVariable("id")Integer[] id){
        //获取删除对象
        Collection<BzFileDO> fileDOS = fileService.listByIds(Arrays.asList(id));
        //更换时间格式前置
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build("https://"+ENDPOINT, ASSET_KEY_ID, ASSET_KEY_SECRET);
        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        for(BzFileDO fileDO:fileDOS){
            ossClient.deleteObject(BUCKET, simpleDateFormat.format(fileDO.getCreateTime())+"/"+fileDO.getNewName());
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        //
        boolean b = fileService.removeByIds(Arrays.asList(id));
        //
        return ResultEntity.ok();
    }
}
